Here is what a switch statement looks like:
switch ( integerExpression )
{
case label1 :
statementList1
break;
case label2 :
statementList2
break;
case label3 :
statementList3
break;
. . . other cases like the above
default:
defaultStatementList
}
|
Here is how it works:
- Only one case will be selected per execution of the
switch statement.
- The value of
integerExpression determines which case is selected.
integerExpression must evaluate to an integer type
(including char ).
- Each
label must be an integer literal (like 0, 23, or 'A'), but not
an expression or variable.
- There can be any number of statements in a
statementList .
- The
statementList is usually followed with break;
- Each time the
switch statement is executed, the following happens:
- The
integerExpression is evaluated.
- The
label s after each case are inspected one by one,
starting with the first.
- The first label that matches has its
statementList execute.
- The statements execute until the
break statement is encountered.
- Now the entire
switch statement is complete.
- If no case label matches the value of
integerExpression , then
the default case is picked, and its statements execute.
|